<template>
  <div class="style-select-page">
    <!-- 搜索栏 -->
    <div class="search-section">
      <van-search
        v-model="searchKeyword"
        placeholder="搜索风格名称"
        @search="onSearch"
        @clear="onClear"
      />
    </div>
    
    <!-- 分类标签 -->
    <div class="category-section">
      <van-tabs v-model:active="activeCategory" @click-tab="onCategoryChange">
        <van-tab name="" title="全部"></van-tab>
        <van-tab 
          v-for="category in categories" 
          :key="category.key"
          :name="category.key" 
          :title="category.name"
        ></van-tab>
      </van-tabs>
    </div>
    
    <!-- 风格网格 -->
    <div class="styles-content">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <div class="styles-grid" v-if="filteredStyles.length > 0">
          <div 
            v-for="style in filteredStyles" 
            :key="style.id"
            class="style-card"
            :class="{ selected: selectedStyle?.id === style.id }"
            @click="selectStyle(style)"
          >
            <!-- 图片区域 -->
            <div class="style-image">
              <img 
                :src="style.thumbnail_url || style.preview_image_url || '/placeholder.jpg'" 
                :alt="style.name"
                @error="onImageError"
              />
              
              <!-- VIP标识 -->
              <div class="premium-badge" v-if="style.is_premium">
                <van-icon name="diamond" />
              </div>
              
              <!-- 选中标识 -->
              <div class="selected-overlay" v-if="selectedStyle?.id === style.id">
                <van-icon name="success" />
              </div>
            </div>
            
            <!-- 信息区域 -->
            <div class="style-info">
              <h3 class="style-name">{{ style.name }}</h3>
              <p class="style-desc">{{ style.description || '专业AI风格生成' }}</p>
              
              <div class="style-meta">
                <div class="meta-item">
                  <van-icon name="eye-o" />
                  <span>{{ style.usage_count }}次使用</span>
                </div>
                <div class="meta-item">
                  <van-icon name="photo" />
                  <span>{{ style.recommended_width }}×{{ style.recommended_height }}</span>
                </div>
              </div>
              
              <!-- 推荐参数 -->
              <div class="style-params">
                <van-tag size="mini" type="primary">{{ style.recommended_steps }}步</van-tag>
                <van-tag size="mini" type="success">CFG {{ style.recommended_cfg_scale }}</van-tag>
                <van-tag size="mini" v-if="style.is_premium" type="warning">VIP</van-tag>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 空状态 -->
        <van-empty 
          v-else-if="!loading" 
          description="没有找到相关风格"
          image="search"
        >
          <van-button 
            type="primary" 
            size="small"
            @click="clearSearch"
          >
            清空搜索
          </van-button>
        </van-empty>
        
        <!-- 加载状态 -->
        <van-loading v-if="loading" class="loading-center" />
      </van-pull-refresh>
    </div>
    
    <!-- 底部确认按钮 -->
    <div class="confirm-section" v-if="selectedStyle">
      <div class="selected-info">
        <div class="selected-image">
          <img 
            :src="selectedStyle.thumbnail_url || selectedStyle.preview_image_url" 
            :alt="selectedStyle.name"
          />
        </div>
        <div class="selected-details">
          <h4>{{ selectedStyle.name }}</h4>
          <p>{{ selectedStyle.description || '专业AI风格生成' }}</p>
        </div>
      </div>
      
      <van-button 
        type="primary" 
        size="large"
        round
        @click="confirmStyle"
        class="confirm-btn"
      >
        确认选择
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useImageStore } from '../stores/image'
import { useUserStore } from '../stores/user'
import type { StyleTemplate, Category } from '../types'
import { Toast } from 'vant'

const router = useRouter()
const imageStore = useImageStore()
const userStore = useUserStore()

const searchKeyword = ref('')
const activeCategory = ref('')
const selectedStyle = ref<StyleTemplate | null>(imageStore.selectedStyle)
const loading = ref(false)
const refreshing = ref(false)
const categories = ref<Category[]>([])

// 计算过滤后的风格列表
const filteredStyles = computed(() => {
  let styles = imageStore.styleTemplates
  
  // 分类筛选
  if (activeCategory.value) {
    styles = styles.filter(style => style.category === activeCategory.value)
  }
  
  // 搜索筛选
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    styles = styles.filter(style => 
      style.name.toLowerCase().includes(keyword) ||
      (style.description && style.description.toLowerCase().includes(keyword))
    )
  }
  
  return styles
})

// 选择风格
const selectStyle = (style: StyleTemplate) => {
  // 检查VIP权限
  if (style.is_premium && userStore.user?.vip_level === 0) {
    Toast('该风格需要VIP权限')
    return
  }
  
  selectedStyle.value = selectedStyle.value?.id === style.id ? null : style
}

// 搜索
const onSearch = (value: string) => {
  searchKeyword.value = value
}

// 清空搜索
const onClear = () => {
  searchKeyword.value = ''
}

const clearSearch = () => {
  searchKeyword.value = ''
  activeCategory.value = ''
}

// 分类切换
const onCategoryChange = async (name: string) => {
  activeCategory.value = name
  await loadStyles(name)
}

// 下拉刷新
const onRefresh = async () => {
  await Promise.all([
    loadStyles(activeCategory.value),
    loadCategories()
  ])
  refreshing.value = false
}

// 图片错误处理
const onImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/placeholder.jpg'
}

// 确认选择风格
const confirmStyle = () => {
  if (!selectedStyle.value) return
  
  imageStore.setSelectedStyle(selectedStyle.value)
  
  // 如果有上传的图片，直接去上传页面，否则提示先上传
  if (imageStore.uploadedImage) {
    router.push('/upload')
  } else {
    Toast('请先上传猫咪照片')
    router.push('/upload')
  }
}

// 加载风格列表
const loadStyles = async (category?: string) => {
  loading.value = true
  
  try {
    const result = await imageStore.loadStyleTemplates(category)
    if (!result.success) {
      Toast.fail(result.error || '加载风格失败')
    }
  } finally {
    loading.value = false
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    const result = await imageStore.loadCategories()
    if (result.success) {
      categories.value = imageStore.categories
    }
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

onMounted(async () => {
  await Promise.all([
    loadStyles(),
    loadCategories()
  ])
})
</script>

<style scoped>
.style-select-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 100px;
}

.search-section {
  padding: 16px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.category-section {
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.styles-content {
  padding: 16px;
}

.styles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.style-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  cursor: pointer;
  transition: all 0.3s ease;
}

.style-card:active {
  transform: translateY(2px);
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.12);
}

.style-card.selected {
  border: 2px solid #6366f1;
  box-shadow: 0 4px 20px rgba(99, 102, 241, 0.3);
}

.style-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.style-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.premium-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(45deg, #ffd700, #ffed4a);
  color: #333;
  border-radius: 50%;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.selected-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(99, 102, 241, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 32px;
}

.style-info {
  padding: 16px;
}

.style-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.style-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
  margin-bottom: 12px;
}

.style-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #999;
}

.meta-item .van-icon {
  font-size: 12px;
}

.style-params {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.confirm-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 16px;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.1);
  border-radius: 20px 20px 0 0;
}

.selected-info {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.selected-image {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.selected-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.selected-details {
  flex: 1;
}

.selected-details h4 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.selected-details p {
  font-size: 12px;
  color: #666;
}

.confirm-btn {
  background: linear-gradient(45deg, #6366f1, #8b5cf6);
  border: none;
  font-weight: bold;
}

.loading-center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

@media (max-width: 768px) {
  .styles-grid {
    grid-template-columns: 1fr;
  }
}
</style>